package com.tc.have_a_tired.ui;

import com.tc.have_a_tired.config.ConfigManager;
import com.tc.have_a_tired.service.RestReminderService;
import com.tc.have_a_tired.util.Constants;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

/**
 * 设置窗口类
 */
public class SettingsWindow extends JDialog {

    private JTextField intervalField;
    private JTextField restDurationField;
    private JTextArea messageArea;
    private JCheckBox useCustomMessageCheckBox;
    private JSlider opacitySlider;
    private JLabel opacityValueLabel;
    private RestReminderService reminderService;
    private SystemTrayManager trayManager;
    private RestCountdownWindow previewWindow; // 实时预览窗口

    public SettingsWindow(Frame parent, RestReminderService reminderService) {
        super(parent, "设置", true);
        this.reminderService = reminderService;
        initUI();
        loadSettings();
    }

    public SettingsWindow(Frame parent, RestReminderService reminderService, SystemTrayManager trayManager) {
        super(parent, "设置", true);
        this.reminderService = reminderService;
        this.trayManager = trayManager;
        initUI();
        loadSettings();
    }

    private void initUI() {
        setSize(550, 600);
        setResizable(false);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        centerWindow();

        // 主面板
        JPanel mainPanel = new JPanel(new BorderLayout(15, 15));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 内容面板
        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));

        // 提醒间隔设置
        JPanel intervalPanel = createInputPanel("提醒间隔（分钟）:",
                Constants.MIN_REMINDER_INTERVAL, Constants.MAX_REMINDER_INTERVAL);
        intervalField = (JTextField) ((JPanel) intervalPanel.getComponent(1)).getComponent(0);
        contentPanel.add(intervalPanel);
        contentPanel.add(Box.createVerticalStrut(15));

        // 休息时长设置
        JPanel restDurationPanel = createInputPanel("休息时长（分钟）:",
                Constants.MIN_REST_DURATION, Constants.MAX_REST_DURATION);
        restDurationField = (JTextField) ((JPanel) restDurationPanel.getComponent(1)).getComponent(0);
        contentPanel.add(restDurationPanel);
        contentPanel.add(Box.createVerticalStrut(15));

        // 分隔线
        contentPanel.add(new JSeparator());
        contentPanel.add(Box.createVerticalStrut(15));

        // 倒计时窗口透明度设置
        JPanel opacityPanel = createOpacityPanel();
        contentPanel.add(opacityPanel);
        contentPanel.add(Box.createVerticalStrut(15));

        // 分隔线
        contentPanel.add(new JSeparator());
        contentPanel.add(Box.createVerticalStrut(15));

        // 自定义提示语设置
        JLabel messageLabel = new JLabel("自定义提示语:");
        messageLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        messageLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        contentPanel.add(messageLabel);
        contentPanel.add(Box.createVerticalStrut(5));

        // 提示语文本区域
        messageArea = new JTextArea(6, 40);
        messageArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        messageArea.setLineWrap(true);
        messageArea.setWrapStyleWord(true);
        messageArea.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLoweredBevelBorder(),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)));

        JScrollPane messageScrollPane = new JScrollPane(messageArea);
        messageScrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
        messageScrollPane.setPreferredSize(new Dimension(500, 120));
        contentPanel.add(messageScrollPane);
        contentPanel.add(Box.createVerticalStrut(10));

        // 使用自定义提示语复选框
        useCustomMessageCheckBox = new JCheckBox("使用自定义提示语");
        useCustomMessageCheckBox.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        useCustomMessageCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT);
        useCustomMessageCheckBox.addActionListener(e -> {
            messageArea.setEnabled(useCustomMessageCheckBox.isSelected());
        });
        contentPanel.add(useCustomMessageCheckBox);
        contentPanel.add(Box.createVerticalStrut(10));

        // 提示语操作按钮
        JPanel messageButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
        messageButtonPanel.setAlignmentX(Component.LEFT_ALIGNMENT);

        JButton restoreDefaultButton = new JButton("恢复默认");
        restoreDefaultButton.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        restoreDefaultButton.addActionListener(e -> {
            messageArea.setText(ConfigManager.getDefaultMessage());
            useCustomMessageCheckBox.setSelected(false);
            messageArea.setEnabled(false);
        });

        JButton previewButton = new JButton("预览效果");
        previewButton.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        previewButton.addActionListener(e -> previewMessage());

        messageButtonPanel.add(restoreDefaultButton);
        messageButtonPanel.add(previewButton);
        contentPanel.add(messageButtonPanel);

        mainPanel.add(contentPanel, BorderLayout.CENTER);

        // 底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));

        ColoredButton saveButton = new ColoredButton(
                "保存",
                new Color(70, 130, 180),
                Color.WHITE,
                new Color(100, 149, 237));
        saveButton.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        saveButton.setPreferredSize(new Dimension(100, 35));
        saveButton.addActionListener(e -> saveSettings());

        JButton cancelButton = new JButton("取消");
        cancelButton.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        cancelButton.setPreferredSize(new Dimension(100, 35));
        cancelButton.addActionListener(e -> dispose());

        ColoredButton exitButton = new ColoredButton(
                "退出程序",
                new Color(220, 20, 60),
                Color.WHITE,
                new Color(255, 50, 80));
        exitButton.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        exitButton.setPreferredSize(new Dimension(100, 35));
        exitButton.addActionListener(e -> {
            int result = JOptionPane.showConfirmDialog(
                    this,
                    "确定要退出程序吗？",
                    "确认退出",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE);
            if (result == JOptionPane.YES_OPTION) {
                if (trayManager != null) {
                    trayManager.exitApplicationDirectly();
                } else {
                    // 如果没有托盘管理器，直接退出
                    if (reminderService != null) {
                        reminderService.stop();
                    }
                    System.exit(0);
                }
            }
        });

        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        buttonPanel.add(exitButton);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        add(mainPanel);

        // 添加窗口监听器
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowOpened(java.awt.event.WindowEvent e) {
                // 窗口显示后创建预览窗口
                SwingUtilities.invokeLater(() -> {
                    createPreviewWindow();
                });
            }

            @Override
            public void windowClosing(java.awt.event.WindowEvent e) {
                closePreviewWindow();
            }

            @Override
            public void windowClosed(java.awt.event.WindowEvent e) {
                closePreviewWindow();
            }
        });

        addComponentListener(new ComponentAdapter() {
            @Override
            public void componentMoved(ComponentEvent e) {
                positionPreviewWindow();
            }

            @Override
            public void componentResized(ComponentEvent e) {
                positionPreviewWindow();
            }
        });
    }

    private JPanel createInputPanel(String labelText, int min, int max) {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setAlignmentX(Component.LEFT_ALIGNMENT);

        JLabel label = new JLabel(labelText);
        label.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        label.setAlignmentX(Component.LEFT_ALIGNMENT);
        panel.add(label);

        JPanel inputPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        JTextField textField = new JTextField(10);
        textField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        textField.setHorizontalAlignment(JTextField.CENTER);
        inputPanel.add(textField);

        JLabel hintLabel = new JLabel(String.format("（范围：%d-%d）", min, max));
        hintLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 11));
        hintLabel.setForeground(Color.GRAY);
        inputPanel.add(hintLabel);

        panel.add(inputPanel);

        return panel;
    }

    private void loadSettings() {
        intervalField.setText(String.valueOf(ConfigManager.getReminderInterval()));
        restDurationField.setText(String.valueOf(ConfigManager.getRestDuration()));

        // 加载透明度设置
        float opacity = ConfigManager.getCountdownOpacity();
        int opacityPercent = (int) (opacity * 100);
        opacitySlider.setValue(opacityPercent);
        updateOpacityLabel(opacityPercent);

        // 注意：预览窗口将在窗口显示后创建（在windowOpened事件中）

        boolean useCustom = ConfigManager.isUseCustomMessage();
        useCustomMessageCheckBox.setSelected(useCustom);
        messageArea.setEnabled(useCustom);

        String customMessage = ConfigManager.getCustomMessage();
        if (useCustom && customMessage != null && !customMessage.isEmpty()) {
            messageArea.setText(customMessage);
        } else {
            messageArea.setText(ConfigManager.getDefaultMessage());
        }
    }

    private void saveSettings() {
        try {
            // 验证并保存提醒间隔
            int interval = Integer.parseInt(intervalField.getText().trim());
            if (interval < Constants.MIN_REMINDER_INTERVAL || interval > Constants.MAX_REMINDER_INTERVAL) {
                JOptionPane.showMessageDialog(this,
                        String.format("提醒间隔必须在 %d-%d 分钟之间！",
                                Constants.MIN_REMINDER_INTERVAL, Constants.MAX_REMINDER_INTERVAL),
                        "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            ConfigManager.setReminderInterval(interval);

            // 验证并保存休息时长
            int restDuration = Integer.parseInt(restDurationField.getText().trim());
            if (restDuration < Constants.MIN_REST_DURATION || restDuration > Constants.MAX_REST_DURATION) {
                JOptionPane.showMessageDialog(this,
                        String.format("休息时长必须在 %d-%d 分钟之间！",
                                Constants.MIN_REST_DURATION, Constants.MAX_REST_DURATION),
                        "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            ConfigManager.setRestDuration(restDuration);

            // 保存透明度设置
            int opacityPercent = opacitySlider.getValue();
            float opacity = opacityPercent / 100.0f;
            if (opacity < Constants.MIN_OPACITY || opacity > Constants.MAX_OPACITY) {
                JOptionPane.showMessageDialog(this,
                        String.format("透明度必须在 %.0f%%-%.0f%% 之间！",
                                Constants.MIN_OPACITY * 100, Constants.MAX_OPACITY * 100),
                        "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            ConfigManager.setCountdownOpacity(opacity);

            // 保存提示语设置
            boolean useCustom = useCustomMessageCheckBox.isSelected();
            ConfigManager.setUseCustomMessage(useCustom);

            String message = messageArea.getText().trim();
            if (message.length() > Constants.MAX_MESSAGE_LENGTH) {
                JOptionPane.showMessageDialog(this,
                        String.format("提示语长度不能超过 %d 个字符！", Constants.MAX_MESSAGE_LENGTH),
                        "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            ConfigManager.setCustomMessage(message);

            // 更新定时器
            if (reminderService != null) {
                reminderService.updateInterval();
            }

            JOptionPane.showMessageDialog(this, "设置已保存！", "成功", JOptionPane.INFORMATION_MESSAGE);
            dispose();

        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "请输入有效的数字！", "输入错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void previewMessage() {
        try {
            int interval = Integer.parseInt(intervalField.getText().trim());
            int restDuration = Integer.parseInt(restDurationField.getText().trim());

            String message;
            if (useCustomMessageCheckBox.isSelected()) {
                message = messageArea.getText().trim();
                if (message.isEmpty()) {
                    message = ConfigManager.getDefaultMessage();
                }
            } else {
                message = ConfigManager.getDefaultMessage();
            }

            String finalMessage = ConfigManager.replaceVariables(message, interval, restDuration);

            // 显示预览窗口
            ReminderWindow previewWindow = new ReminderWindow(finalMessage, restDuration, null);
            previewWindow.setTitle("预览效果");
            previewWindow.setVisible(true);

        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "请先输入有效的间隔和时长！", "预览失败", JOptionPane.WARNING_MESSAGE);
        }
    }

    /**
     * 创建透明度设置面板
     */
    private JPanel createOpacityPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 标题标签
        JLabel label = new JLabel("倒计时窗口透明度:");
        label.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        label.setAlignmentX(Component.LEFT_ALIGNMENT);
        panel.add(label);
        panel.add(Box.createVerticalStrut(5));

        // 滑块和数值显示面板
        JPanel sliderPanel = new JPanel(new BorderLayout(10, 0));
        sliderPanel.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 透明度滑块
        opacitySlider = new JSlider(
                (int) (Constants.MIN_OPACITY * 100),
                (int) (Constants.MAX_OPACITY * 100),
                (int) (Constants.DEFAULT_COUNTDOWN_OPACITY * 100));
        opacitySlider.setMajorTickSpacing(20);
        opacitySlider.setMinorTickSpacing(5);
        opacitySlider.setPaintTicks(true);
        opacitySlider.setPaintLabels(true);
        opacitySlider.setFont(new Font("Microsoft YaHei", Font.PLAIN, 10));
        opacitySlider.addChangeListener(e -> {
            // 无论是否在拖动，都实时更新（实现真正的实时预览）
            int value = opacitySlider.getValue();
            updateOpacityLabel(value);
            // 实时更新预览窗口的透明度
            updatePreviewOpacity(value);
        });

        // 当前值标签
        opacityValueLabel = new JLabel();
        opacityValueLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        opacityValueLabel.setForeground(new Color(70, 130, 180));
        opacityValueLabel.setPreferredSize(new Dimension(80, 20));
        updateOpacityLabel(opacitySlider.getValue());

        sliderPanel.add(opacitySlider, BorderLayout.CENTER);
        sliderPanel.add(opacityValueLabel, BorderLayout.EAST);

        panel.add(sliderPanel);
        panel.add(Box.createVerticalStrut(5));

        // 提示信息
        JLabel hintLabel = new JLabel("提示：拖动滑块可实时预览透明度效果（范围：10%-100%）");
        hintLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 11));
        hintLabel.setForeground(Color.GRAY);
        hintLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        panel.add(hintLabel);

        return panel;
    }

    /**
     * 更新透明度标签显示
     */
    private void updateOpacityLabel(int percent) {
        opacityValueLabel.setText(String.format("%d%%", percent));
    }

    /**
     * 创建实时预览窗口
     */
    private void createPreviewWindow() {
        try {
            // 如果预览窗口已存在，先关闭它
            closePreviewWindow();

            // 创建新的预览窗口（使用5分钟作为固定显示时间）
            previewWindow = new RestCountdownWindow(5, null);
            previewWindow.setTitle("透明度实时预览");

            // 设置为预览模式（显示固定时间，不进行倒计时）
            previewWindow.setPreviewMode(5);

            // 设置预览窗口位置（在设置窗口右侧）
            positionPreviewWindow();

            // 设置初始背景透明度（只影响背景，不影响文字）
            int opacityPercent = opacitySlider.getValue();
            float opacity = opacityPercent / 100.0f;
            previewWindow.updateBackgroundOpacity(opacity);

            previewWindow.setVisible(true);

            // 初次显示时同步位置
            positionPreviewWindow();
        } catch (Exception e) {
            System.err.println("创建预览窗口失败: " + e.getMessage());
        }
    }

    /**
     * 同步预览窗口位置，使其跟随设置窗口移动
     */
    private void positionPreviewWindow() {
        if (previewWindow == null || !previewWindow.isShowing()) {
            return;
        }

        SwingUtilities.invokeLater(() -> {
            if (previewWindow == null) {
                return;
            }

            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            int previewX = getX() + getWidth() + 20;
            int previewY = getY();

            // 如果超出屏幕右侧，则放到左侧
            if (previewX + previewWindow.getWidth() > screenSize.width) {
                previewX = getX() - previewWindow.getWidth() - 20;
            }

            // 确保在屏幕范围内
            if (previewX < 20) {
                previewX = 20;
            } else if (previewX + previewWindow.getWidth() > screenSize.width - 20) {
                previewX = screenSize.width - previewWindow.getWidth() - 20;
            }

            if (previewY < 20) {
                previewY = 20;
            } else if (previewY + previewWindow.getHeight() > screenSize.height - 20) {
                previewY = screenSize.height - previewWindow.getHeight() - 20;
            }

            previewWindow.setLocation(previewX, previewY);
        });
    }

    /**
     * 实时更新预览窗口的透明度
     */
    private void updatePreviewOpacity(int opacityPercent) {
        // 在EDT线程中更新，确保实时响应
        SwingUtilities.invokeLater(() -> {
            if (previewWindow != null && previewWindow.isVisible()) {
                float opacity = opacityPercent / 100.0f;
                // 更新背景透明度（只影响背景，不影响文字）
                previewWindow.updateBackgroundOpacity(opacity);
                positionPreviewWindow();
            } else {
                // 如果预览窗口不存在或已关闭，重新创建
                createPreviewWindow();
            }
        });
    }

    /**
     * 关闭预览窗口
     */
    private void closePreviewWindow() {
        if (previewWindow != null) {
            try {
                previewWindow.dispose();
            } catch (Exception e) {
                // 忽略关闭时的异常
            }
            previewWindow = null;
        }
    }

    private void centerWindow() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (screenSize.width - getWidth()) / 2;
        int y = (screenSize.height - getHeight()) / 2;
        setLocation(x, y);
    }
}
